﻿using System.Configuration;
using System.Linq;

namespace Medianamik.Service.ActiveDirectory.Configuration
{
    public class ActiveDirectoryConfigService : ConfigurationSection, IActiveDirectoryConfigService
    {
        public const string LDAP_SERVER_NAME = "serverName";
        public const string DOMAIN_USERNAME = "domainUsername";
        public const string DOMAIN_PASSWORD = "domainPassword";
        public const string REDIRECT_URL = "redirectUrlWhenLogged";
        public const string WEBCONFIG_SECTION_NAME = "MedianamikService.ActiveDirectory";

        [ConfigurationProperty(LDAP_SERVER_NAME, DefaultValue = "")]
        public string ServerName
        {
            get { return (string)base[LDAP_SERVER_NAME]; }
            set { base[LDAP_SERVER_NAME] = value; }
        }

        [ConfigurationProperty(DOMAIN_USERNAME, DefaultValue = "")]
        public string DomainUsername
        {
            get { return (string)base[DOMAIN_USERNAME]; }
            set { base[DOMAIN_USERNAME] = value; }
        }

        [ConfigurationProperty(DOMAIN_PASSWORD, DefaultValue = "")]
        public string DomainPassword
        {
            get { return (string)base[DOMAIN_PASSWORD]; }
            set { base[DOMAIN_PASSWORD] = value; }
        }

        [ConfigurationProperty(REDIRECT_URL, DefaultValue = "/medianamik")]
        public string RedirectUrlWhenLogged
        {
            get
            {
                var url = (string) base[REDIRECT_URL];
                return url.StartsWith("/") ? url : "/" + url;
            }
            set { base[REDIRECT_URL] = value; }
        }

        public IActiveDirectoryConfigService GetInstance()
        {
            return Instance();
        }

        public static IActiveDirectoryConfigService Instance()
        {
            return (ActiveDirectoryConfigService)ConfigurationManager.GetSection(WEBCONFIG_SECTION_NAME);
        }
    }

    public interface IActiveDirectoryConfigService
    {
        string ServerName { get; set; }
        string DomainUsername { get; set; }
        string DomainPassword { get; set; }
        string RedirectUrlWhenLogged { get; set; }
    }
}
